<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Utils\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * 拦截同一个token同一个方法连续的post请求
 * Class FilterPostMiddleware.
 */
class FilterPostMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var \Hyperf\HttpServer\Contract\ResponseInterface
     */
    protected $response;

    public function __construct(ContainerInterface $container, RequestInterface $request, \Hyperf\HttpServer\Contract\ResponseInterface $response)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $this->request->header('token');
        $requestUri = $this->request->getRequestUri();
        $redis = Redis::getInstance();
        $redisKey = $token . '_' . $requestUri;
        if ($this->request->isMethod('POST') && ! empty($token)) {
            if (! $redis->setnx($redisKey, '1')) {
                return $this->response->json([
                    'code' => ErrorCode::BUSY_ERROE,
                    'msg' => ErrorCode::getMessage(ErrorCode::BUSY_ERROE),
                ]);
            }
            $redis->expire($redisKey, 3);
        }
        $ret = $handler->handle($request);
        $redis->del($redisKey);
        return $ret;
    }
}
